package cn.lctvu.filter;

import cn.lctvu.bean.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter("/admin/*")
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        HttpServletRequest request=(HttpServletRequest) req;
        HttpSession session=request.getSession();
        PrintWriter out=resp.getWriter();
        if(request.getServletPath().equals("/admin/login.jsp") || request.getServletPath().equals("/admin/LoginServlet")
                || request.getServletPath().endsWith(".css")){
            chain.doFilter(req, resp);
        }else {
            User user=(User) session.getAttribute("user");
            if(user==null){
                out.print("<script language='javascript'>alert('没有权限登录，请返回登录');document.location.href='/admin/login.jsp';</script>");
                return;
            }else {
                chain.doFilter(req, resp);
            }
        }


    }

    public void init(FilterConfig config) throws ServletException {

    }

}
